package com.hy.main.utils.object;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.TreeMap;

/**
 * @author fancy
 * @date 2021/7/6 5:47 下午
 */
public class ObjUtl {

    public static TreeMap<String, String> getParamsJson(JSONObject jsonObject) {
        TreeMap<String, String> map = new TreeMap<>();
        if (jsonObject == null) {
            return new TreeMap<>();
        }
        jsonObject.forEach((k, v) -> {
            if (v == null) {
                return;
            }

            if (v instanceof String) {
                map.put(k, v.toString());
            } else {
                map.put(k, JSON.toJSONString(v));
            }
        });
        return map;
    }


    /**
     * 动态遍历获取所有收到的参数
     */
    public static TreeMap<String, String> getParams(Object data) throws IllegalAccessException {
        if (data == null) {
            return new TreeMap<>();
        }

        TreeMap<String, String> map = new TreeMap<>();
        Field[] fields = data.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object val = field.get(data);
            if (val == null || "".equals(val.toString())) {
                continue;
            }
            if (val instanceof Collection) {
                map.put(field.getName(), JSON.toJSONString(val));
                continue;
            }
            // 这里加上trim，防止出现空格导致加密失败
            map.put(field.getName(), val.toString().trim());
        }
        return map;
    }
}
